package com.milhouz.bomberrokon;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

public class ResultRoundActivity extends Activity {

	private List<BomberVictories> bomberVictories;

	private View mMainMenuButton;
	private TextView mResultTextView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.result_round_dialog);

		// Get activity inputs
		final Intent callingIntent = this.getIntent();
		int nbOpponents = callingIntent.getIntExtra("opponents", 1);
		bomberVictories = new ArrayList<BomberVictories>();
		for (int i = 0; i < nbOpponents + 1; i++) {
			bomberVictories.add(new BomberVictories(i, callingIntent.getIntExtra("PLAYER" + i, 0)));
		}

		// Set Result Text View
		mResultTextView = (TextView) findViewById(R.id.resultInfoText);
		mResultTextView.setText(formatResultList());

		// Set Main Menu Button
		mMainMenuButton = findViewById(R.id.resultToMainMenuButton);
		mMainMenuButton.setOnClickListener(sMainMenuButtonListener);
	}

	private String formatResultList() {
		Collections.sort(bomberVictories);
		Collections.reverse(bomberVictories);
		StringBuffer result = new StringBuffer("Match Result\n");
		result.append("\nBomber ").append(bomberVictories.get(0).getIdBomber() + 1).append(" wins the match !!!\n\n");
		for (BomberVictories bomberVic : bomberVictories) {
			result.append("Bomber " + (bomberVic.getIdBomber() + 1) + ". " + bomberVic.getNbVictories());
			result.append("\n");
		}
		return result.toString();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return true;
	}

	private View.OnClickListener sMainMenuButtonListener = new View.OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent(getBaseContext(), MainMenuActivity.class);
			startActivity(i);
		}
	};

	private class BomberVictories implements Comparable<BomberVictories> {
		private int idBomber;
		private int nbVictories;

		public BomberVictories(int idBomber, int nbVictories) {
			this.idBomber = idBomber;
			this.nbVictories = nbVictories;
		}

		public int getIdBomber() {
			return idBomber;
		}

		public int getNbVictories() {
			return nbVictories;
		}

		@Override
		public int compareTo(BomberVictories another) {
			if (nbVictories < another.getNbVictories()) {
				return -1;
			} else if (nbVictories > another.getNbVictories()) {
				return 1;
			}
			return 0;
		}

	}

}
